﻿
var subscriptionKey;
var groupId;

function getKeys() {
    $.ajax({
        dataType: 'json',
        contentType: 'application/json',
        url: 'keys.json',
        type: "GET",
        async: false,
        success: function (data) {
            var keys = data;
            subscriptionKey = keys.subscriptionkey;
            groupId = keys.groupid;
        },
        error: function (data) {
            alert("Could not retrieve keys");
            console.log(data);
        }
    });
}


function createList() {

    var persons = [];
    
    $.ajax({
        url: "https://api.projectoxford.ai/face/v0/persongroups/" + groupId + "/persons?subscription-key=" + subscriptionKey,
        type: 'GET',
        success: function (data) {
            persons = data;
            var list = document.getElementById("personList");

            for (var i = 0; i < persons.length; i++) {
                var row = list.insertRow(1);
                var userId = row.insertCell(0);
                var username = row.insertCell(1);
                var userdata = row.insertCell(2);
                var editBtn = row.insertCell(3);
                var deleteBtn = row.insertCell(4);
                userId.innerHTML = "<p>" + persons[i].personId + "</p>";
                username.innerHTML = "<p>" + persons[i].name + "</p>";
                userdata.innerHTML = "<p>" + persons[i].userData + "</p>";
                editBtn.innerHTML = "<button type='button' class='btn btn-primary' style='margin:12px' onclick='editRedirect(\"" + persons[i].personId + "\")'>View / Edit</button>";
                deleteBtn.innerHTML = "<button type='button' class='btn-sm btn-danger' style='margin:12px' onclick='deletePerson(\"" + persons[i].personId + "\", \"" + persons[i].name + "\")'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button>";
            }
        },
        error: function(data) {
            console.log(data);
            var obj = JSON.parse(data.responseText);
            alert("Error: " + obj.message);
        }
    });
}


function personSearch() {
    var persons = [];
    var key = document.getElementById("searchbar").value;

    $.ajax({
        url: "https://api.projectoxford.ai/face/v0/persongroups/" + groupId + "/persons?subscription-key=" + subscriptionKey,
        type: 'GET',
        success: function (data) {
            persons = data;
            var list = document.getElementById("personList");
            var L = list.rows.length
            for (var i = 0; i < L - 1; i++) {
                list.deleteRow(1);
            }
            for (var i = 0; i < persons.length; i++) {
                if (persons[i].personId == key || persons[i].name == key) {
                    var row = list.insertRow(1);
                    var userId = row.insertCell(0);
                    var username = row.insertCell(1);
                    var userdata = row.insertCell(2);
                    var editBtn = row.insertCell(3);
                    var deleteBtn = row.insertCell(4);
                    userId.innerHTML = "<p>" + persons[i].personId + "</p>";
                    username.innerHTML = "<p>" + persons[i].name + "</p>";
                    userdata.innerHTML = "<p>" + persons[i].userData + "</p>";
                    editBtn.innerHTML = "<button type='button' class='btn btn-primary' style='margin:12px' onclick='editRedirect(\"" + persons[i].personId + "\")'>View / Edit</button>";
                    deleteBtn.innerHTML = "<button type='button' class='btn-sm btn-danger' style='margin:12px' onclick='deletePerson(\"" + persons[i].personId + "\", \"" + persons[i].name + "\")'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button>";
                }
            }
        },
        error: function (data) {
            console.log(data);
            var obj = JSON.parse(data.responseText);
            alert("Error: " + obj.message);
        }
    });
}


function faceSearch() {
    var persons = [];
    var key = document.getElementById("searchbar").value;

    $.ajax({
        url: "https://api.projectoxford.ai/face/v0/persongroups/" + groupId + "/persons?subscription-key=" + subscriptionKey,
        type: 'GET',
        success: function (data) {
            persons = data;
            var list = document.getElementById("faceList");
            var L = list.rows.length
            for (var i = 0; i < L - 1; i++) {
                list.deleteRow(1);
            }
            for (var i = 0; i < persons.length; i++) {
                if (persons[i].faceIds != null) {
                    for (var j = 0; j < persons[i].faceIds.length; j++) {
                        if (key == persons[i].faceIds[j] || key == persons[i].personId || key == persons[i].name) {
                            var row = list.insertRow(1);
                            var FaceId = row.insertCell(0);
                            var userId = row.insertCell(1);
                            var username = row.insertCell(2);
                            var facedata = row.insertCell(3);
                            var infoBtn = row.insertCell(4);
                            var deleteBtn = row.insertCell(5);

                            FaceId.innerHTML = "<p>" + persons[i].faceIds[j] + "</p>";
                            userId.innerHTML = "<p>" + persons[i].personId + "</p>";
                            username.innerHTML = "<p>" + persons[i].name + "</p>";
                            infoBtn.innerHTML = "<span id='" + i + "-" + j + "'><button type='button' class='btn-sm btn-primary' style='margin:12px' onclick='showInfo(\"" + persons[i].personId + "\", \"" + persons[i].faceIds[j] + "\", \"" + i + "-" + j + "\")'>File / URL</button></span>";
                            deleteBtn.innerHTML = "<button type='button' class='btn-sm btn-danger' style='margin:12px' onclick='deleteFace(\"" + persons[i].personId + "\", \"" + persons[i].faceIds[j] + "\")'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button>";
                        }
                    }
                }
            }
        },
        error: function (data) {
            console.log(data);
            var obj = JSON.parse(data.responseText);
            alert("Error: " + obj.message);
        }
    });
}

function editRedirect(userId) {
    window.location = "http://localhost:28273/EditPerson?id=" + userId;
}

function editGroupRedirect(groupId) {
    window.location = "http://localhost:28273/EditGroup?id=" + groupId;
}

function setupEditPage(userId) {
    var username;
    var faceId = [];
    var userdata;
    $.ajax({
        url: "https://api.projectoxford.ai/face/v0/persongroups/" + groupId + "/persons?subscription-key=" + subscriptionKey,
        type: 'GET',
        success: function (data) {
            persons = data;

            for (var i = 0; i < persons.length; i++) {
                if(persons[i].personId == userId) {
                    username = persons[i].name;
                    userdata = persons[i].userData;
                    faceId = persons[i].faceIds;
                }
            }

            document.getElementById('editHeader').innerHTML += ": " + username;
            document.getElementById('username').value = username;
            document.getElementById('userdata').value = userdata;

            for (var i = 0; i < faceId.length; i++) {
                document.getElementById('faceIdList').innerHTML += "<option value='" + faceId[i] + "'>" + faceId[i] + "</option>";
            }
        },
        error: function(data) {
            console.log(data);
            var obj = JSON.parse(data.responseText);
            alert("Error: " + obj.message);
        }
    });
}

function setupGroupEdit(groupId) {
    var name;
    var userdata;

    $.ajax({
        url: "https://api.projectoxford.ai/face/v0/persongroups?subscription-key=" + subscriptionKey,
        type: 'GET',
        success: function (data) {
            groups = data;
            
            for (var i = 0; i < groups.length; i++) {
                if (groups[i].personGroupId == groupId) {
                    name = groups[i].name;
                    userdata = groups[i].userData;
                }
            }

            document.getElementById('editHeader').innerHTML += ": " + groupId;
            document.getElementById('name').value = name;
            document.getElementById('userdata').value = userdata;
        },
        error: function (data) {
            console.log(data);
            var obj = JSON.parse(data.responseText);
            alert("Error: " + obj.message);
        }
    });

}

function loadImageFile() {

    var fileSelect = document.getElementById("faceIdFile").files;
    if (fileSelect.length > 0) {
        var file = fileSelect[0];
        var fileReader = new FileReader();
        var dataUrl;
        fileReader.onload = function (fileLoadedEvent) {
            dataUrl = fileLoadedEvent.target.result;

            var byteString;
            if (dataUrl.split(',')[0].indexOf('base64') >= 0)
                byteString = atob(dataUrl.split(',')[1]);
            else
                byteString = unescape(dataUrl.split(',')[1]);

            var mimeString = dataUrl.split(',')[0].split(':')[1].split(';')[0];

            var ia = new Uint8Array(byteString.length);
            for (var i = 0; i < byteString.length; i++) {
                ia[i] = byteString.charCodeAt(i);
            }

            var blob = new Blob([ia], { type: mimeString });
            detectFace(blob);
        };
        fileReader.readAsDataURL(file);
    }
}

function detectFace(blob) {

    var params = {
        'subscription-key': subscriptionKey,
        analyzesFaceLandmarks: "true",
        analyzesAge: "true",
        analyzesGender: "true",
        analyzesHeadPose: "true"
    };
    
    $.ajax({
        url: "https://api.projectoxford.ai/face/v0/detections?" + $.param(params),
        type: 'POST',
        data: blob,
        contentType: 'application/octet-stream',
        processData: false,
        success: function (data) {
            document.getElementById("faceId").value = data[0].faceId;
        },
        error: function (data) {
            console.log(data);
            var obj = JSON.parse(data.responseText);
            alert("Error: " + obj.message);
        }
    }); 

}

function createPerson() {
    var username = document.getElementById("username").value;
    var userdata = document.getElementById("userdata").value;

    $.ajax({
        url: "https://api.projectoxford.ai/face/v0/persongroups/" + groupId + "/persons?subscription-key=" + subscriptionKey,
        type: 'POST',
        data: JSON.stringify({
            "name": username,
            "userData": userdata
        }),
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            alert("Created Person Successfully");
            location.reload();
        },
        error: function (data) {
            console.log(data);
            var obj = JSON.parse(data.responseText);
            alert("Error: " + obj.message);
        }
    });
}

function deletePerson(personId, personName) {
    var accept = confirm("Are you sure you want to delete " + personName + "?");
    if (accept == true) {
        $.ajax({
            url: "https://api.projectoxford.ai/face/v0/persongroups/" + groupId + "/persons/" + personId + "?subscription-key=" + subscriptionKey,
            type: 'DELETE',
            success: function () {
                alert("Successfully deleted user");
                location.reload();
            },
            error: function (data) {
                console.log(data);
                var obj = JSON.parse(data.responseText);
                alert("Error: " + obj.message);
            }
        });
    }
}

function deleteFaceId(userId) {
    var element = document.getElementById('faceIdList');
    var faceId = element.options[element.selectedIndex].value;
    deleteFace(userId, faceId);
}


function addFileFaceId(userId) {
    var faceId = document.getElementById('faceId').value;
    var userdata = document.getElementById('picdata').value;
    addFace(userId, faceId, userdata);
}

function addUrlFaceId(userId) {
    var userdata = document.getElementById('picdata').value;
    var params = {
        'subscription-key': subscriptionKey,
        analyzesFaceLandmarks: "true",
        analyzesAge: "true",
        analyzesGender: "true",
        analyzesHeadPose: "true"
    };

    $.ajax({
        url: "https://api.projectoxford.ai/face/v0/detections?" + $.param(params),
        type: 'POST',
        data: JSON.stringify({
            "url": faceUrl
        }),
        dataType: 'json',
        contentType: 'application/json',
        success: function (data) {
            var faceId = data[0].faceId;
            addFace(userId, faceId, userdata);
        },
        error: function (data) {
            console.log(data);
            var obj = JSON.parse(data.responseText);
            alert("Error: " + obj.message);
        }
    });
}

function updatePerson(userId) {
    var username = document.getElementById('username').value;
    var userdata = document.getElementById('userdata').value;
    var faceId = [];
    var accept = confirm("Are you sure you want to update user info?");
    if (accept == true) {
        $.ajax({
            url: "https://api.projectoxford.ai/face/v0/persongroups/" + groupId + "/persons?subscription-key=" + subscriptionKey,
            type: 'GET',
            success: function (data) {
                persons = data;

                for (var i = 0; i < persons.length; i++) {
                    if (persons[i].personId == userId) {
                        faceId = persons[i].faceIds;
                    }
                }

                $.ajax({
                    url: 'https://api.projectoxford.ai/face/v0/persongroups/' + groupId + '/persons/' + userId + '?subscription-key=' + subscriptionKey,
                    type: 'PATCH',
                    data: JSON.stringify({
                        "faceIds": faceId,
                        "name": username,
                        "userData": userdata
                    }),
                    dataType: 'json',
                    contentType: 'application/json',
                    success: function () {
                        document.getElementById('redirect').click();
                    },
                    error: function (data) {
                        console.log(data);
                        var obj = JSON.parse(data.responseText);
                        alert("Error: " + obj.message);
                    }
                });
            }
        });
    }
}

function createFaceList() {
    var persons = [];

    $.ajax({
        url: "https://api.projectoxford.ai/face/v0/persongroups/" + groupId + "/persons?subscription-key=" + subscriptionKey,
        type: 'GET',
        success: function (data) {
            persons = data;
            var list = document.getElementById("faceList");

            for (var i = 0; i < persons.length; i++) {
                if (persons[i].faceIds != null) {
                    for (var j = 0; j < persons[i].faceIds.length; j++) {
                        var row = list.insertRow(1);
                        var FaceId = row.insertCell(0);
                        var userId = row.insertCell(1);
                        var username = row.insertCell(2);
                        var facedata = row.insertCell(3);
                        var infoBtn = row.insertCell(4);
                        var deleteBtn = row.insertCell(5);

                        FaceId.innerHTML = "<p>" + persons[i].faceIds[j] + "</p>";
                        userId.innerHTML = "<p>" + persons[i].personId + "</p>";
                        username.innerHTML = "<p>" + persons[i].name + "</p>";
                        infoBtn.innerHTML = "<span id='" + i + "-" + j + "'><button type='button' class='btn-sm btn-primary' style='margin:12px' onclick='showInfo(\"" + persons[i].personId + "\", \"" + persons[i].faceIds[j] + "\", \"" + i + "-" + j + "\")'>User Data</button></span>";
                        deleteBtn.innerHTML = "<button type='button' class='btn-sm btn-danger' style='margin:12px' onclick='deleteFace(\"" + persons[i].personId + "\", \"" + persons[i].faceIds[j] + "\")'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button>";
                    }
                }
            }
        },
        error: function (data) {
            console.log(data);
            var obj = JSON.parse(data.responseText);
            alert("Error: " + obj.message);
        }
    });
}

function showInfo(person, faceId, cellId) {
    $.ajax({
        url: 'https://api.projectoxford.ai/face/v0/persongroups/' + groupId + '/persons/' + person + '/faces/' + faceId + '?subscription-key=' + subscriptionKey,
        type: 'GET',
        success: function (data) {
            document.getElementById(cellId).innerHTML = "<p>" + data.userData + "</p>";
        },
        error: function (data) {
            console.log(data);
            var obj = JSON.parse(data.responseText);
            alert("Error: " + obj.message);
        }
    });
}

function addFace(userId, faceId, userdata) {
    $.ajax({
        url: 'https://api.projectoxford.ai/face/v0/persongroups/' + groupId + '/persons/' + userId + '/faces/' + faceId + '?subscription-key=' + subscriptionKey,
        type: 'PUT',
        data: JSON.stringify({userData: userdata}),
        dataType: 'json',
        contentType: 'application/json',
        success: function () {
            alert('Face Added');
            location.reload();
        },
        error: function (data) {
            console.log(data);
            var obj = data;
            if (obj.status == 200) {
                alert('Face Added');
                location.reload();
            }
            else {
                console.log(data);
                var obj = JSON.parse(data.responseText);
                alert("Error: " + obj.message);
            }
        }
    });
}

function deleteFace(userId, faceId) {
    var accept = confirm("Are you sure you want to delete this face ID?");
    if (accept == true) {
        $.ajax({
            url: 'https://api.projectoxford.ai/face/v0/persongroups/' + groupId + '/persons/' + userId + '/faces/' + faceId + '?subscription-key=' + subscriptionKey,
            type: 'DELETE',
            success: function () {
                alert("Successfully deleted face ID");
                location.reload();
            },
            error: function (data) {
                console.log(data);
                var obj = JSON.parse(data.responseText);
                alert("Error: " + obj.message);
            }
        });
    }
}

function createGroup() {
    var groupId = document.getElementById('groupId').value;
    var groupname = document.getElementById('groupname').value;
    var userdata = document.getElementById('userdata').value;
    $.ajax({
        url: 'https://api.projectoxford.ai/face/v0/persongroups/' + groupId + '?subscription-key=' + subscriptionKey,
        type: 'PUT',
        data: JSON.stringify({
            "name": groupname,
            "userData": userdata
        }),
        dataType: 'json',
        contentType: 'application/json',
        success: function () {
            alert("Created Person Group Successfully");
            location.reload();
        },
        error: function (data) {
            console.log(data);
            if (data.status == 200) {
                alert('Created Person Group Successfully');
                location.reload();
            }
            else {
                console.log(data);
                var obj = JSON.parse(data.responseText);
                alert("Error: " + obj.message);
            }
        }
    });
}

function createGroupList() {

    var groups = [];

    $.ajax({
        url: "https://api.projectoxford.ai/face/v0/persongroups?subscription-key=" + subscriptionKey,
        type: 'GET',
        success: function (data) {
            groups = data;
            var list = document.getElementById("groupList");

            for (var i = 0; i < groups.length; i++) {
                var row = list.insertRow(1);
                var groupId = row.insertCell(0);
                var groupname = row.insertCell(1);
                var userdata = row.insertCell(2);
                var defaultBtn = row.insertCell(3);
                var editBtn = row.insertCell(4);
                var deleteBtn = row.insertCell(5);

                groupId.innerHTML = "<p>" + groups[i].personGroupId + "</p>";
                groupname.innerHTML = "<p>" + groups[i].name + "</p>";
                userdata.innerHTML = "<p>" + groups[i].userData + "</p>";
                defaultBtn.innerHTML = "<button type='button' class='btn btn-primary' style='margin:12px' onclick='setDefaultGroup(\"" + groups[i].personGroupId + "\");'>Set As Default</button>";
                editBtn.innerHTML = "<button type='button' class='btn btn-primary' style='margin:12px' onclick='editGroupRedirect(\"" + groups[i].personGroupId + "\")'>Edit</button>";
                deleteBtn.innerHTML = "<button type='button' class='btn-sm btn-danger' style='margin:12px' onclick='deleteGroup(\"" + groups[i].personGroupId + "\")'><span class='glyphicon glyphicon-remove' aria-hidden='true'></span></button>";
            }
        },
        error: function (data) {
            console.log(data);
            var obj = JSON.parse(data.responseText);
            alert("Error: " + obj.message);
        }
    });
}

function deleteGroup(groupId) {
    var accept = confirm("Are you sure you want to delete " + groupId + "?");
    if (accept == true) {
        $.ajax({
            url: 'https://api.projectoxford.ai/face/v0/persongroups/' + groupId + '?subscription-key=' + subscriptionKey,
            type: 'DELETE',
            success: function () {
                alert("Successfully deleted group");
                location.reload();
            },
            error: function (data) {
                console.log(data);
                var obj = JSON.parse(data.responseText);
                alert("Error: " + obj.message);
            }
        });
    }
}

function updateGroup(groupId) {
    name = document.getElementById('name').value;
    userdata = document.getElementById('userdata').value;

    $.ajax({
        url: 'https://api.projectoxford.ai/face/v0/persongroups/' + groupId + '?subscription-key=' + subscriptionKey,
        type: 'PATCH',
        data: JSON.stringify({
            "name": name,
            "userData": userdata
        }),
        dataType: 'json',
        contentType: 'application/json',
        success: function () {
            document.getElementById('redirect').click();
        },
        error: function (data) {
            if (data.status == 200) {
                document.getElementById('redirect').click();
            }
            else {
                console.log(data);
                var obj = JSON.parse(data.responseText);
                alert("Error: " + obj.message);
            }
        }
    });
}
